import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """自定义jwt扩展登录视图的响应数据函数"""
    return {
        'user_id':user.id,
        'username':user.username,
        'token':token

    }

def get_user_by_account(account):
    """account :用户名或手机号"""
    try:
        if re.match(r'1[3-9]\d{9}$',account):
            user=User.objects.get(mobile=account)
        else:
            user=User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user

# 自定Django认证后端类
class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self,request,username=None,password=None, **kwargs):
        """username:用户名或手机号"""
        #1.根据'用户名'或'手机号'
        user=get_user_by_account(username)
        #2.验证用户名密码,如果密码登录,返回user
        if user and user.check_password(password):
            #帐号密码正确
            return user

    # def authenticate(self, request, username=None, password=None, **kwargs):
    #     if username is None:
    #         username = kwargs.get(UserModel.USERNAME_FIELD)
    #     try:
    #         user = UserModel._default_manager.get_by_natural_key(username)
    #     except UserModel.DoesNotExist:
    #         # Run the default password hasher once to reduce the timing
    #         # difference between an existing and a non-existing user (#20760).
    #         UserModel().set_password(password)
    #     else:
    #         if user.check_password(password) and self.user_can_authenticate(user):
    #             return user